// 获取应用实例
const app = getApp<IAppOption>()
import { http } from '../../services/http'
import { beerService } from '../../services/beer'

interface FlavorOption {
  name: string;
  selected: boolean;
}

interface BeerData {
  name: string;
  type: string;
  description: string;
  abv: string;
  ibu: string;
  origin: string;
  tasteNotes: string;
  foodPairing: string;
}

// 模拟啤酒数据库
const MOCK_BEER_DATABASE: BeerData[] = [
  {
    name: "黑森林世涛",
    type: "俄罗斯帝国世涛",
    description: "这款黑森林世涛融合了巧克力麦芽的浓郁与樱桃的微酸，酒体饱满，泡沫细腻持久。入口丝滑，尾韵带有轻微的烤面包与咖啡风味。",
    abv: "9.5%",
    ibu: "55",
    origin: "比利时",
    tasteNotes: "浓郁的烤麦芽香气，带有明显的黑巧克力和咖啡风味，中等偏高的酒精感，入口醇厚，余味悠长带有樱桃和葡萄干的甜感。",
    foodPairing: "巧克力甜点、蓝纹奶酪、烤牛排、浓郁的炖肉"
  },
  {
    name: "柑橘狂潮IPA",
    type: "新英格兰IPA",
    description: "这款柑橘狂潮IPA带有浓郁的热带水果和柑橘香气，酒体轻盈，浑浊如橙汁。苦味节制，以突出现代美国和新西兰酒花的果香。",
    abv: "6.8%",
    ibu: "45",
    origin: "美国",
    tasteNotes: "爆炸性的柑橘、芒果和菠萝香气，微弱的麦芽甜感，适中的苦味平衡，收尾干爽带有柚子皮的清香。",
    foodPairing: "墨西哥塔可、烧烤海鲜、泰式咖喱、水果沙拉"
  },
  {
    name: "松针云海",
    type: "西海岸IPA",
    description: "这款西海岸IPA突出展现了松木和松针的独特风味，同时保持清爽平衡。苦味突出但不过分，酒体中等，余味干净。",
    abv: "7.2%",
    ibu: "70",
    origin: "美国",
    tasteNotes: "强烈的松木、松针香气，伴随着柑橘和松脂的复杂层次，麦芽backbone提供平衡，尾韵干爽带有持久的苦味。",
    foodPairing: "辛辣食物、烧烤猪肉、浓郁的奶酪、烤三文鱼"
  },
  {
    name: "香草拿铁世涛",
    type: "牛奶世涛",
    description: "这款牛奶世涛充满了香草、咖啡和巧克力的诱人风味，酒体饱满顺滑，泡沫如奶油般丝滑。入口甜美但不腻口，余韵深长。",
    abv: "5.8%",
    ibu: "28",
    origin: "爱尔兰",
    tasteNotes: "浓郁的烤麦芽、咖啡、牛奶巧克力香气，明显的香草风味，甜度适中，酒体丝滑如天鹅绒，几乎没有酒精感。",
    foodPairing: "巧克力布朗尼、提拉米苏、奶酪蛋糕、冰淇淋"
  },
  {
    name: "烟熏枫糖波特",
    type: "波特啤酒",
    description: "这款波特啤酒融合了轻微的烟熏风味与枫糖的甜香，层次丰富而不失平衡。酒体中等偏重，色泽深褐，泡沫米色持久。",
    abv: "6.5%",
    ibu: "35",
    origin: "加拿大",
    tasteNotes: "明显的烟熏风味与焦糖、枫糖的甜味完美融合，带有轻微的咖啡和黑巧克力尾韵，余味中等长度带有坚果香气。",
    foodPairing: "烟熏肉类、烧烤猪肉、枫糖煎饼、枫糖培根"
  },
  {
    name: "酸樱桃野啤",
    type: "比利时兰比克啤酒",
    description: "这款传统风格的樱桃兰比克啤酒采用野生酵母自然发酵，带有明显的酸味和樱桃风味。酒体轻盈，碳酸适中，余味干爽。",
    abv: "5.0%",
    ibu: "15",
    origin: "比利时",
    tasteNotes: "浓郁的樱桃香气，明显的酸味带有谷仓和橡木桶的复杂风味，微妙的甜度平衡了酸味，收尾干爽带有樱桃核的轻微苦杏仁香。",
    foodPairing: "鸭肉、山羊奶酪、巧克力甜点、水果派"
  }
];

Component({
  data: {
    flavorOptions: [
      // 基础口感特点
      { name: '清爽型', selected: false },
      { name: '浓郁型', selected: false },
      { name: '平衡型', selected: false },
      
      // 香气/风味特点
      { name: '酒花香', selected: false },
      { name: '柑橘香', selected: false },
      { name: '热带水果', selected: false },
      { name: '松木/松针', selected: false },
      { name: '草本植物', selected: false },
      { name: '花香', selected: false },
      { name: '麦芽甜', selected: false },
      { name: '烤面包', selected: false },
      { name: '焦糖', selected: false },
      { name: '咖啡味', selected: false },
      { name: '巧克力味', selected: false },
      { name: '香草味', selected: false },
      { name: '烟熏味', selected: false },
      
      // 口味强度
      { name: '苦味强', selected: false },
      { name: '苦味温和', selected: false },
      { name: '酸味', selected: false },
      { name: '甜味', selected: false },
      { name: '辛辣味', selected: false },
      
      // 酒精度偏好
      { name: '低酒精', selected: false },
      { name: '高酒精', selected: false }
    ] as FlavorOption[],
    selectedFlavors: [] as string[],
    customFlavor: '',
    isLoading: false,
    resultContent: '',
    streamTaskId: null as WechatMiniprogram.RequestTask | null,
    showResult: false,
    beerData: {} as BeerData
  },
  methods: {
    // 切换口味选择
    toggleFlavor(e: any) {
      const index = e.currentTarget.dataset.index;
      const option = this.data.flavorOptions[index];
      const selected = !option.selected;
      
      this.setData({
        [`flavorOptions[${index}].selected`]: selected
      });
      
      // 更新选中的口味列表
      const selectedFlavors = this.data.flavorOptions
        .filter(item => item.selected)
        .map(item => item.name);
      
      this.setData({
        selectedFlavors
      });
    },
    
    // 处理自定义口味输入
    onCustomFlavorInput(e: any) {
      this.setData({
        customFlavor: e.detail.value
      });
    },
    
    // 提交请求
    submitRequest() {
      const { selectedFlavors, customFlavor } = this.data;
      
      if (selectedFlavors.length === 0 && !customFlavor) {
        wx.showToast({
          title: '请至少选择一种口味或填写自定义口味',
          icon: 'none'
        });
        return;
      }
      
      this.setData({
        isLoading: true,
        showResult: true
      });
      
      // 使用模拟数据，而不是发送实际请求
      this.simulateRecommendation();
    },
    
    // 模拟生成推荐
    simulateRecommendation() {
      const { selectedFlavors, customFlavor } = this.data;
      const self = this;
      
      // 根据选择的口味来匹配最合适的啤酒
      setTimeout(() => {
        // 简单的匹配逻辑：为每个啤酒分配一个分数，基于与用户选择的匹配程度
        let bestMatch: BeerData | null = null;
        let highestScore = -1;
        
        for (const beer of MOCK_BEER_DATABASE) {
          let score = 0;
          
          // 对每种啤酒进行评分
          if (selectedFlavors.includes('清爽型') && beer.type.includes('IPA') && !beer.type.includes('帝国')) {
            score += 2;
          }
          
          if (selectedFlavors.includes('浓郁型') && (beer.type.includes('世涛') || beer.type.includes('波特'))) {
            score += 2;
          }
          
          if (selectedFlavors.includes('酒花香') && beer.type.includes('IPA')) {
            score += 2;
          }
          
          if (selectedFlavors.includes('柑橘香') && beer.name.includes('柑橘')) {
            score += 3;
          }
          
          if (selectedFlavors.includes('松木/松针') && beer.name.includes('松针')) {
            score += 3;
          }
          
          if ((selectedFlavors.includes('咖啡味') || selectedFlavors.includes('巧克力味')) && 
              (beer.description.includes('咖啡') || beer.description.includes('巧克力'))) {
            score += 2;
          }
          
          if (selectedFlavors.includes('香草味') && beer.name.includes('香草')) {
            score += 3;
          }
          
          if (selectedFlavors.includes('烟熏味') && beer.name.includes('烟熏')) {
            score += 3;
          }
          
          if (selectedFlavors.includes('酸味') && beer.type.includes('兰比克')) {
            score += 3;
          }
          
          if (selectedFlavors.includes('苦味强') && parseInt(beer.ibu) > 60) {
            score += 2;
          }
          
          if (selectedFlavors.includes('苦味温和') && parseInt(beer.ibu) < 40) {
            score += 2;
          }
          
          if (selectedFlavors.includes('高酒精') && parseFloat(beer.abv) > 7) {
            score += 2;
          }
          
          if (selectedFlavors.includes('低酒精') && parseFloat(beer.abv) < 6) {
            score += 2;
          }
          
          // 更新最佳匹配
          if (score > highestScore) {
            highestScore = score;
            bestMatch = beer;
          }
        }
        
        // 如果没有好的匹配，随机选择一个
        if (bestMatch === null || highestScore < 2) {
          const randomIndex = Math.floor(Math.random() * MOCK_BEER_DATABASE.length);
          bestMatch = MOCK_BEER_DATABASE[randomIndex];
        }
        
        // 更新UI
        self.setData({
          isLoading: false,
          beerData: bestMatch
        });
      }, 2000); // 模拟加载延迟2秒
    },
    
    // 返回选择页面
    backToSelection() {
      this.setData({
        showResult: false,
        isLoading: false
      });
    },
    
    // 发起流式请求（目前未使用）
    startStreamRequest(flavorPreference: string) {
      const url = beerService.getStreamRecommendationUrl();
      const self = this;
      
      // 创建请求任务
      const task = wx.request({
        url: 'https://okeydo.fourcats.online' + url,
        method: 'POST',
        data: {
          preference: flavorPreference
        },
        header: {
          'content-type': 'application/json',
          'Accept': 'text/event-stream',
          'X-API-KEY': 'c4608807-6562-41ac-9574-381250f2c41b'
        },
        enableChunked: true, // 启用分块传输
        success: (res: any) => {
          console.log('Stream request completed', res);
        },
        fail: (err) => {
          console.error('Stream request failed', err);
          wx.showToast({
            title: '网络异常',
            icon: 'none'
          });
          self.setData({
            isLoading: false
          });
        },
        complete: () => {
          self.setData({
            isLoading: false,
            streamTaskId: null
          });
        }
      });
      
      // 监听数据块返回
      task.onChunkReceived((response) => {
        try {
          // 将二进制数据转换为文本
          const text = String.fromCharCode.apply(null, new Uint8Array(response.data) as unknown as number[]);
          const chunk = text;
          
          // 处理SSE格式数据
          if (chunk.startsWith('data:')) {
            const content = chunk.slice(5).trim();
            
            if (content === '[DONE]') {
              // 流结束标记
              return;
            }
            
            try {
              // 尝试解析JSON
              const data = JSON.parse(content);
              if (data.text) {
                // 追加内容
                self.setData({
                  resultContent: self.data.resultContent + data.text
                });
              }
            } catch (e) {
              // 如果不是JSON，直接添加文本
              self.setData({
                resultContent: self.data.resultContent + content
              });
            }
          }
        } catch (error) {
          console.error('Error processing chunk', error);
        }
      });
      
      // 保存任务ID，以便可以取消
      this.setData({
        streamTaskId: task
      });
    },
    
    // 页面销毁时取消未完成的请求
    onUnload() {
      if (this.data.streamTaskId) {
        this.data.streamTaskId.abort();
      }
    }
  },
  lifetimes: {
    attached() {
      // 组件创建时执行的代码
    },
    detached() {
      // 组件销毁时执行的代码
      if (this.data.streamTaskId) {
        this.data.streamTaskId.abort();
      }
    }
  }
}) 